﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using nspLib;

namespace NextStep_V1._0.Model.Util
{
    class DBUtils
    {
        SqlConnection conn = new SqlConnection(new ConnectUtils().SQL_CONNECTION_STRING);
        SqlCommand cmd;
        SqlDataAdapter da;
        DataTable tb;
        SqlDataReader read;
        public void BackupBAK(String databaseName, String filePath)
        {
            try
            {
                Server server = new Server();
                Backup backup = new Backup();
                backup.Devices.AddDevice(filePath, DeviceType.File);
                backup.Database = databaseName;
                backup.Action = BackupActionType.Database;
                backup.SqlBackup(server);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }

        }

        public void BackupDatabase(String databaseName, String userName, 
            String serverName, String password, String destinationPath)
        {
            Backup sqlBackup = new Backup();
            sqlBackup.Action = BackupActionType.Database;
            sqlBackup.BackupSetDescription = "NextStepDatabe:" + DateTime.Now.ToShortDateString();
            sqlBackup.BackupSetName = "NextStep";
            sqlBackup.Database = databaseName;

            BackupDeviceItem deviceItem = default(BackupDeviceItem);
            deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);

            ServerConnection connection = new ServerConnection(serverName, userName, password);
            Server sqlServer = new Server(connection);
            Database db = sqlServer.Databases[databaseName];

            sqlBackup.Initialize = true;
            sqlBackup.Checksum = true;
            sqlBackup.ContinueAfterError = true;

            sqlBackup.Devices.Add(deviceItem);
            sqlBackup.Incremental = false;

            sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
            sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

            sqlBackup.FormatMedia = false;
            sqlBackup.SqlBackup(sqlServer);
        }

        public void RestoreDatabase(String databaseName, String filePath, String serverName, String userName,
            String password, String dataFilePath, String logFilePath)
        {
            Restore sqlRestore = new Restore();
            BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
            sqlRestore.Devices.Add(deviceItem);
            sqlRestore.Database = databaseName;

            ServerConnection connection = new ServerConnection(serverName, userName, password);
            Server sqlServer = new Server(connection);
            Database db = sqlServer.Databases[databaseName];
            sqlRestore.Action = RestoreActionType.Database;

            String dataFileLocation = dataFilePath + databaseName + ".mdf";
            String logFileLocation = logFilePath + databaseName + "_Log.ldf";

            db = sqlServer.Databases[databaseName];

            RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
            sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
            sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
            sqlRestore.ReplaceDatabase = true;
            sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
            sqlRestore.PercentCompleteNotification = 10;
            sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);

            sqlRestore.SqlRestore(sqlServer);
            db = sqlServer.Databases[databaseName];
            db.SetOnline();
            sqlServer.Refresh();
        }

        public event EventHandler<PercentCompleteEventArgs> PercentComplete;

        void sqlRestore_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            if (PercentComplete != null)
                PercentComplete(sender, e);
        }

        public event EventHandler<ServerMessageEventArgs> Complete;

        public void sqlRestore_Complete(object sender, ServerMessageEventArgs e)
        {
            if (Complete != null)
                Complete(sender, e);
        }

        //ham kiem tra da co don vi co so ton tai hay chua
        public Boolean getBaseUnit()
        {
            String sql = "SELECT * FROM BS_BASE_UNIT";
            cmd = new SqlCommand(sql, conn);
            conn.Open();
            read = cmd.ExecuteReader();
            if (read.HasRows == true)
            {
                conn.Close();
                return false;
            }
            else
            {
                conn.Close();
                return true;
            }
            
        }
    }
}
